package com.fingerth.crawler.room

import androidx.room.TypeConverter
import java.util.*
import kotlin.collections.ArrayList

class Converters {
    companion object {
        const val C_SPLIT = "%@@-&&%"
    }

    @TypeConverter
    fun longToDate(l: Long): Date = Date(l)

    @TypeConverter
    fun dateToLong(date: Date) = date.time

    @TypeConverter
    fun arrayToString(list: ArrayList<String>?): String {
        val sb = StringBuilder()
        if (!list.isNullOrEmpty()) {
            for ((i, s1) in list.withIndex()) {
                val s = s1.replace("\\n", "")
                if (i == 0) sb.append(s) else sb.append(C_SPLIT).append(s)
            }
        }
        return sb.toString()
    }

    @TypeConverter
    fun string2Array(str: String?): ArrayList<String> {
        return if (str.isNullOrBlank()) {
            arrayListOf()
        } else {
            val l = str.split(C_SPLIT)
            ArrayList(l)
        }
    }

//    @TypeConverter
//    fun fromLocation(location: Location): String {
//        return JSONObject().apply {
//            put("lng", location.lng)
//            put("lat", location.lat)
//        }.toString()
//    }
//
//    @TypeConverter
//    fun toLocation(location: String): Location {
//        val json = JSONObject(location)
//        return Location(json.getString("lng"), json.getString("lat"))
//    }
}